/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.util;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.SerializableEntity;

import android.os.AsyncTask;
import android.util.Log;

public abstract class NetworkHandlerTask<Params, Progress, Result> extends AsyncTask<Params, Progress, Result>{

    protected Object doNetworkPost(String url, Serializable o) throws Exception {
        
        URI uri = new URI("http", url, null);

        Log.i(Global.LOG_TAG, "Sending Network post at [" + uri + "]");

        HttpPost p = new HttpPost(uri);
        SerializableEntity en = new SerializableEntity(o, true);
        p.setEntity(en);

        HttpResponse response = HttpManager.execute(p);

        HttpEntity entity = null;
        try {
            entity = response.getEntity();
            final ObjectInputStream ois = new ObjectInputStream(entity.getContent());
            return ois.readObject();
        } finally {
            if (entity != null) {
                try {
                    entity.consumeContent();
                } catch (IOException e) {
                    Log.e(Global.LOG_TAG, "Could not load image from " + url, e);
                }
            }
        }
    }
}
